import 'package:flutter/material.dart';

class UnitConversionPage extends StatefulWidget {
  @override
  _UnitConversionPageState createState() => _UnitConversionPageState();
}

class _UnitConversionPageState extends State<UnitConversionPage> {
  final units = ['m', 'km', 'cm'];
  String fromUnit = 'm';
  String toUnit = 'km';
  final inputController = TextEditingController();
  String result = '';

  void convert() {
    double inputValue = double.tryParse(inputController.text) ?? 0;
    double convertedValue;

    if (fromUnit == 'm' && toUnit == 'km') {
      convertedValue = inputValue / 1000;
    } else if (fromUnit == 'm' && toUnit == 'cm') {
      convertedValue = inputValue * 100;
    } else if (fromUnit == 'km' && toUnit == 'm') {
      convertedValue = inputValue * 1000;
    } else if (fromUnit == 'km' && toUnit == 'cm') {
      convertedValue = inputValue * 100000;
    } else if (fromUnit == 'cm' && toUnit == 'm') {
      convertedValue = inputValue / 100;
    } else if (fromUnit == 'cm' && toUnit == 'km') {
      convertedValue = inputValue / 100000;
    } else {
      convertedValue = inputValue;
    }

    setState(() {
      result = '$inputValue $fromUnit = $convertedValue $toUnit';
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('单位换算'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          children: [
            TextField(
              controller: inputController,
              keyboardType: TextInputType.number,
              decoration: InputDecoration(
                labelText: '输入值',
              ),
            ),
            DropdownButton<String>(
              value: fromUnit,
              items: units.map((unit) {
                return DropdownMenuItem(
                  value: unit,
                  child: Text(unit),
                );
              }).toList(),
              onChanged: (value) {
                setState(() {
                  fromUnit = value!;
                });
              },
            ),
            DropdownButton<String>(
              value: toUnit,
              items: units.map((unit) {
                return DropdownMenuItem(
                  value: unit,
                  child: Text(unit),
                );
              }).toList(),
              onChanged: (value) {
                setState(() {
                  toUnit = value!;
                });
              },
            ),
            ElevatedButton(
              onPressed: convert,
              child: Text('换算'),
            ),
            Text(result),
          ],
        ),
      ),
    );
  }
}